/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: RateDataManager.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.data_manager;


import android.content.SharedPreferences;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.baselib.utils.DebugLog;
import io.bhex.sdk.BhexSdk;
import io.bhex.sdk.quote.bean.NewRatesResponse;
import io.bhex.sdk.quote.bean.RateBean;
import io.bhex.sdk.quote.bean.RatesResponse;
import io.bhex.sdk.Urls;
import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.core.Preferences;
import io.bhex.baselib.network.BParamsBuilder;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.HttpUtils;
import io.bhex.baselib.network.params.GetParams;
import io.bhex.baselib.network.params.IParams;
import io.bhex.baselib.utils.NumberUtils;


public class RateDataManager {


    private static RateDataManager mInstance;
    private SharedPreferences mPrefs;
    public static final String PREFERENCE_RARES = "rates";
    private Timer timer;
    private TimerTask task;
    private static final int nPeriod = 5 * 1000;


    private HashMap<String, HashMap<String,String>> currentRateMap;//汇率map

    public static RateDataManager GetInstance(){
        if(mInstance == null)
            mInstance = new RateDataManager();

        return mInstance;
    }

    private RateDataManager(){
        mPrefs = Preferences.getInstance(CApplication.getInstance()).getSharePref();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
//                GetRates();
                GetNewRates();
            }
        };
        InitRateData();
    }

    private void InitRateData(){
        timer.schedule(task, nPeriod,  nPeriod);

        try {
            String gsonString = mPrefs.getString(PREFERENCE_RARES , "");
            if (!gsonString.isEmpty()) {
                Gson gson = new Gson();
                NewRatesResponse data = gson.fromJson(gsonString, new TypeToken<NewRatesResponse>() {
                }.getType());
                saveRatesToMem(data);
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }

    public void release() {
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.purge();
            timer.cancel();
        }
        mInstance = null;
    }

    public String valueOfPrice(String tokenId,String price) {

        String money="";
        if (TextUtils.isEmpty(tokenId)||TextUtils.isEmpty(price)||"null".equals(price)){
            return money;
        }
        if (currentRateMap != null) {
            HashMap<String,String> rateBean = currentRateMap.get(tokenId);
            if (rateBean != null) {
                String rate;
                switch (RateAndLocalManager.GetInstance(CApplication.getInstance()).getCurRateKind()){
                    case CNY:
                        rate = rateBean.get(RateAndLocalManager.RateKind.CNY.code);
                        break;
                    case USD:
                        rate = rateBean.get(RateAndLocalManager.RateKind.USD.code);
                        break;
                    case KRW:
                        rate = rateBean.get(RateAndLocalManager.RateKind.KRW.code);
                        break;
                    case JPY:
                        rate = rateBean.get(RateAndLocalManager.RateKind.JPY.code);
                        break;
                    case VND:
                        rate = rateBean.get(RateAndLocalManager.RateKind.VND.code);
                        break;
                    default:
                        rate = rateBean.get(RateAndLocalManager.RateKind.USD.code);
                }

//                float legalCurrencyF = new BigDecimal(price).multiply(new BigDecimal(rate)).floatValue();
                double legalCurrencyF = NumberUtils.mul(price,rate);
                money = String.valueOf(legalCurrencyF);
            }
        }else{
//            GetRates();
            GetNewRates();
        }

        return money;
    }


    private void saveRatesToNative(NewRatesResponse response) {
        if (response != null) {
            try {
                SharedPreferences.Editor prefEditor = mPrefs.edit();

                Gson gson = new Gson();
                String gsonString = gson.toJson(response, new TypeToken<NewRatesResponse>() {
                }.getType());
                if (gsonString != null && !"".equals(gsonString)) {
                    prefEditor.putString(PREFERENCE_RARES, gsonString);
                    //同步
                    //prefEditor.commit();
                    prefEditor.apply();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void GetRates(){
        GetParams.Builder builder = BParamsBuilder.get().url(Urls.API_BASIC_RATES_URL);
        IParams params = builder.build();
        HttpUtils.getInstance().request(params, RatesResponse.class, new SimpleResponseListener<RatesResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(RatesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
//                    saveRatesToMem(response);
//                    saveRatesToNative(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * v1 新汇率接口
     */
    public void GetNewRates(){
        String tokenListStr = SymbolDataManager.GetInstance().getTokenListStr();
//        String quoteTokenListStr = SymbolDataManager.GetInstance().getQuoteTokenListStr();
        String quoteTokenListStr = ",BTC,USDT";
        String ratesReq = RateAndLocalManager.GetInstance(BhexSdk.getContext()).getRatesReq();
        String tokens = tokenListStr;
        String legalCoins = ratesReq + "," + quoteTokenListStr;
//        if (!legalCoins.contains("BTC,") && !legalCoins.contains(",BTC")) {
//            legalCoins = legalCoins +",BTC";
//        }
//        if (!legalCoins.contains("USDT,") && !legalCoins.contains(",USDT")) {
//            legalCoins = legalCoins +",USDT";
//        }
        DebugLog.e("XXXX","tokens = "+tokenListStr +"  \n  ratesReq = "+ratesReq+"   \n  quoteTokenListStr = "+quoteTokenListStr);
        GetParams.Builder builder = BParamsBuilder.get().url(Urls.V1_BASIC_RATES_URL);
        IParams params = builder
                .addParam("tokens",tokens)
                .addParam("legalCoins",legalCoins)
                .build();
        HttpUtils.getInstance().request(params, NewRatesResponse.class, new SimpleResponseListener<NewRatesResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(NewRatesResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    saveRatesToMem(response);
                    saveRatesToNative(response);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 保存到内存
     * @param response
     */
    private  void saveRatesToMem(NewRatesResponse response) {
        HashMap<String, HashMap<String,String>> ratesMap = new HashMap<>();
        List<RateBean> datas = response.getData();
        if (datas != null) {
            if (!datas.isEmpty()) {
                for (RateBean data : datas) {
                    if (data != null) {
                        String tokenId = data.getToken();
                        if(!TextUtils.isEmpty(tokenId) && tokenId.equalsIgnoreCase("USDT")){
                            setRatesPriceToUSD(data.getRates());
                        }
                        ratesMap.put(tokenId,data.getRates());
                    }
                }
                currentRateMap = ratesMap;
            }
        }
    }

    /**
     *
     * @param data
     */
    private void setRatesPriceToUSD(HashMap<String,String> data){
        RateAndLocalManager.RateKind.USD.priceToUSD = data.get(RateAndLocalManager.RateKind.USD.code);
        RateAndLocalManager.RateKind.CNY.priceToUSD = data.get(RateAndLocalManager.RateKind.CNY.code);
        RateAndLocalManager.RateKind.KRW.priceToUSD = data.get(RateAndLocalManager.RateKind.KRW.code);
        RateAndLocalManager.RateKind.JPY.priceToUSD = data.get(RateAndLocalManager.RateKind.JPY.code);
        RateAndLocalManager.RateKind.VND.priceToUSD = data.get(RateAndLocalManager.RateKind.VND.code);
    }

    /**
     *  当前汇率换算价
     *  get CurRatePrice
     * @param tokenId
     * @param price
     * @return String
     */
    public static String CurRatePrice(String tokenId, String price){
        return RateDataManager.GetInstance().valueOfPrice(tokenId, price);
    }

    /**
     * 转换法币显示样式 以及格式化小数位数
     * @param legalMoney
     * @param digitNum
     *
     *     ≈
     */
    public static String getShowLegalMoney(String legalMoney, int digitNum) {
        digitNum = NumberUtils.calLegalMoneyDigit(legalMoney,digitNum);
        String showMoney;
        if (TextUtils.isEmpty(legalMoney)){
            showMoney = NumberUtils.roundFormatDown("0",digitNum);
        }else{
            showMoney = NumberUtils.roundFormatDown(legalMoney,digitNum);
        }
        showMoney = CurRateSymbol()+showMoney;
        return showMoney;
    }


    public String TokenToBTC(String token, String usdtPrice){
        String money = "";
        if(currentRateMap != null) {
            HashMap<String,String> rateBean = currentRateMap.get(token);
            if(rateBean != null) {
                double legalCurrencyF = NumberUtils.mul(usdtPrice,rateBean.get("BTC"));
                money = String.valueOf(legalCurrencyF);

            }
        }
        return money;
    }
    public static String getTokenToBTC(String token, String usdtPrice){
        return RateDataManager.GetInstance().TokenToBTC(token, usdtPrice);
    }

    public String BTCToUSDT(String btcPrice){
        String money = "";
        if(currentRateMap != null) {
            HashMap<String,String> rateBean = currentRateMap.get("BTC");
            if(rateBean != null) {
                double legalCurrencyF = NumberUtils.mul(btcPrice,rateBean.get("USDT"));
                money = String.valueOf(legalCurrencyF);

            }
        }
        return money;
    }
    public static String getBTCToUSDT(String btcPrice){
        return RateDataManager.GetInstance().BTCToUSDT(btcPrice);
    }

    /**
     * 获取当前计价货币符号
     * @return
     */
    public static String CurRateSymbol(){
        return RateAndLocalManager.GetInstance(CApplication.getInstance()).getCurRateKind().symbol;
    }

    /**
     * 获取当前计价货币简写
     * @return
     */
    public static String CurRateCode(){
        return RateAndLocalManager.GetInstance(CApplication.getInstance()).getCurRateKind().code;
    }

    /**
     * 获取当前计价货币名字
     * @return
     */
    public static String CurRateName(){
        return RateAndLocalManager.GetInstance(CApplication.getInstance()).getCurRateKind().name;
    }

}
